<template>
  <div class="app-container">
    <!-- 已选打分人 -->
    <el-row style="border:1px solid #dfe6ec">
      <div style="margin:10px 0px 10px 10px;">已选人员：</div>
      <div style="margin:10px 0px 30px 10px;">
        <el-tag style="margin-right:10px;"
                v-for="tag in taskScoreUserlist"
                :key="tag.id"
                closable
                @close="handleTagScoreClose(tag)"
        >
          {{tag.userName}}
        </el-tag>
      </div>
    </el-row>
    <el-row style="margin:10px 5px 5px 0; padding:20px;border:1px solid #dfe6ec" type="flex" align="middle">
      <el-col :span="8">
        <el-row type="flex" align="middle">
          <el-col :span="10">归属部门</el-col>
          <el-col>
            <el-select v-model="paramsScoreUser.sydeName" placeholder="请选择" @change="onRemoteMethod" clearable>
              <el-option v-for="item in deptList" :key="item.label" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="8">
        <el-row type="flex" justify="space-around" align="middle">
          <el-col :span="10">&nbsp;姓 名</el-col>
          <el-col>
            <el-input placeholder="请输入姓名" style="width:150px"
                      v-model="paramsScoreUser.userName" clearable size="small">
            </el-input>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="4">
        <div style="float:right">
          <el-button type="primary" @click="getScoreUserList()">查询</el-button>
        </div>
      </el-col>
    </el-row>
    <div style=" border:1px solid #dfe6ec; margin: 5px 0 10px 0">
      <el-table
        v-if="isMultiple"
        style="width:100%;"
        ref="scoreUserTable"
        :row-key="getRowKeys"
        :data="scoreUserList"
        tooltip-effect="dark"
        @selection-change="handleSoreTableSelectionChange"
        row-class-name="score-el-table__row">

        <el-table-column type="selection" style="width:20%" :reserve-selection="true"/>
        <el-table-column label="序号" type="index"/>
        <el-table-column label="用户姓名" style="width:20%">
          <template slot-scope="scope">{{ scope.row.sysuName}}</template>
        </el-table-column>
        <el-table-column label="用户账号" style="width:30%">
          <template slot-scope="scope">{{ scope.row.userName}}</template>
        </el-table-column>
        <el-table-column label="所属部门" style="width:30%">
          <template slot-scope="scope">{{ scope.row.sydeName}}</template>
        </el-table-column>
      </el-table>

      <el-table
        v-else
        style="width:100%;"
        ref="scoreUserTable"
        :row-key="getRowKeys"
        :data="scoreUserList"
        tooltip-effect="dark"
        highlight-current-row
        @current-change="handleSoreTableSelectionChange"
        row-class-name="score-el-table__row">

        <el-table-column label="序号" type="index"/>
        <el-table-column label="用户姓名" style="width:20%">
          <template slot-scope="scope">{{ scope.row.sysuName}}</template>
        </el-table-column>
        <el-table-column label="用户账号" style="width:40%">
          <template slot-scope="scope">{{ scope.row.userName}}</template>
        </el-table-column>
        <el-table-column label="所属部门" style="width:40%">
          <template slot-scope="scope">{{ scope.row.sydeName}}</template>
        </el-table-column>
      </el-table>
      <pagination style="margin:0 0 20px 0" v-show="scoreUserTotal > 0" :total="scoreUserTotal"
                  :page.sync="paramsScoreUser.pageNum" :limit.sync="paramsScoreUser.pageSize"
                  @pagination="getScoreUserList"/>
    </div>
    <el-row type="flex" justify="center" align="middle" style="margin-top:20px;">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit()">确 定</el-button>
    </el-row>
  </div>
</template>

<script>
    import {userEvItem} from "@/api/teacher/evaluation/task.js";
    import {treeselectAll} from "@/api/system/dept";

    export default {
        name: "deptUser",
        props: {
            processId: String,
            isShow: Boolean,
            multiple: Boolean
        },
        data() {
            return {
                isMultiple: true,
                activities: [],
                taskScoreUserlist: [],
                scoreUserList: [],
                params: {},
                deptList: [],
                scoreUserTotal: 0,
                // 打分人查询参数
                paramsScoreUser: {
                    pageNum: 1,
                    pageSize: 10,
                    sydeName: "",
                    userName: "",
                },
                form: {}
            };
        },

        created() {
            if (this.multiple == false) {
                this.isMultiple = this.multiple
            } else {
                this.isMultiple = true
            }
            //受评人加载方法
            this.onRemoteMethod();
            //打分人加载方法
            this.getScoreUserList();
            treeselectAll().then(res => {
                this.deptList = res.data;
                this.getAllChildDept(this.deptList);
            })
        },
        methods: {
            submit() {

                this.$emit('getTaskUser', this.taskScoreUserlist, false)
            },
            close() {
                this.$emit('getTaskUser', [], false)
            },
            onRemoteMethod(setVal) {
                console.log(setVal);
                let params = {
                    pageNum: 1,
                    pageSize: 10,
                    sydeName: "",
                }

                params.sydeName = setVal;
                userEvItem(params).then(res => {
                    this.scoreUserList = res.data.list;
                    this.scoreUserTotal = res.data.total;
                    this.refreshTableScoreCheck();
                });
            },
            getAllChildDept(deptList) {
                if (deptList && deptList.length) {
                    for (let i = 0; i < deptList.length; i++) {
                        if (deptList[i].children) {
                            let list = deptList[i].children.map((item) => {
                                if (item.children) {
                                    this.getAllChildDept(item.children)
                                }
                                return {
                                    value: deptList[i].id + ',' + item.id,
                                    label: item.label
                                }
                            })
                            this.deptList.push(...list)
                        }
                    }
                }
            },
            getRowKeys(row) {
                return row.id;
            },
            // 刷新分数据（分页重新加载数据时使用，tag标签中的数据进行自动选中的数据（,根据最终存储情况清除掉））
            refreshTableScoreCheck() {
                // var tempScorePageRowsObj = Array.from(this.$refs.scoreUserTable.$el.getElementsByClassName('el-table__row'));
                var notExistList = [];
                if (this.grade) {
                    for (var i = 0, size = this.$refs.scoreUserTable.selection.length; i < size; i++) {
                        //console.log("refreshTableScoreCheck", this.$refs.scoreUserTable.selection[i].id);
                        var exist = false;
                        for (var j = 0, jSize = this.taskScoreUserlist.length; j < jSize; j++) {
                            //console.log(this.$refs.scoreUserTable.selection[i].id, this.taskScoreUserlist[j].id);
                            if (this.$refs.scoreUserTable.selection[i].id == this.taskScoreUserlist[j].id) {
                                exist = true;
                                break;
                            }
                        }
                        if (!exist) {
                            notExistList.push(this.$refs.scoreUserTable.selection[i]);
                        }
                    }
                    for (var i = 0, iSize = notExistList.length; i < iSize; i++) {
                        this.$refs.scoreUserTable.toggleRowSelection(notExistList[i], false);
                    }
                }
            },
            getScoreUserList() {
                userEvItem(this.paramsScoreUser).then(res => {
                    this.scoreUserList = res.data.list;
                    this.scoreUserTotal = res.data.total;
                    this.refreshTableScoreCheck();
                })
            },
            // 打分人：把当前确认选择的打分人，删除单个的方法
            handleTagScoreClose(tag) {
                var canelSelectRow = undefined;
                for (var i = 0, size = this.$refs.scoreUserTable.selection.length; i < size; i++) {
                    // console.log("handleTagScoreClose",tag, this.$refs.scoreUserTable.selection[i]);
                    if (tag.id == this.$refs.scoreUserTable.selection[i].id) {
                        canelSelectRow = this.$refs.scoreUserTable.selection[i];
                    }
                }
                if (canelSelectRow != undefined) {
                    this.$refs.scoreUserTable.toggleRowSelection(canelSelectRow, false);
                }
                // tag 标签移除
                let index = this.taskScoreUserlist.indexOf(tag); // 标签索引
                this.taskScoreUserlist.splice(index, 1); // 移除标签

                this.taskScoreUserIdsRefresh();
            },
            //打分人：table列表多选框选中数据方法
            handleSoreTableSelectionChange(selection) {
                // 当前选择的用户
                if (selection instanceof Array) {

                    this.tempAddScoreUserList = selection;
                } else {
                    this.tempAddScoreUserList = [selection]
                }

                //console.log("this.taskScoreUserlist", this.taskScoreUserlist);
                //console.log("this.tempAddScoreUserList", this.tempAddScoreUserList);
                //1、 把表格中选中的数据 =》 设置到tag中【追加】
                let notExistList = [];
                for (let i = 0, iSize = this.tempAddScoreUserList.length; i < iSize; i++) {
                    var exist = false;
                    for (let j = 0, jSize = this.taskScoreUserlist.length; j < jSize; j++) {
                        if (this.tempAddScoreUserList[i].id == this.taskScoreUserlist[j].id) {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        notExistList.push(this.tempAddScoreUserList[i]);
                    }
                }
                this.taskScoreUserlist.push(...notExistList);
                //console.log("this.taskScoreUserlist", this.taskScoreUserlist);

                //2、 把表格中选中没有选中的数据，从tag中【移除】
                // var tempScorePageRowsObj = Array.from(this.$refs.scoreUserTable.$el.getElementsByClassName('score-el-table__row')); 获取dom对象（这里没有用到）
                let notSelectList = [];
                for (let i = 0, iSize = this.scoreUserList.length; i < iSize; i++) {
                    //console.log("scoreUserList.name", this.scoreUserList[i].userName," this.scoreUserList[i].id", this.scoreUserList[i].id )
                    var exist = false;
                    for (let j = 0, jSize = this.tempAddScoreUserList.length; j < jSize; j++) {
                        //console.log("tempAddScoreUserList[j].userName", this.tempAddScoreUserList[j].userName," this.tempAddScoreUserList[j].id", this.tempAddScoreUserList[j].id);
                        if (this.scoreUserList[i].id == this.tempAddScoreUserList[j].id) {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        notSelectList.push(this.scoreUserList[i]);
                    }
                }
                //console.log("notSelectList.size:", notSelectList.length );

                let needRemoveTagList = [];
                for (var i = 0, isize = notSelectList.length; i < isize; i++) {
                    // tag 标签移除
                    for (var j = 0, jsize = this.taskScoreUserlist.length; j < jsize; j++) {
                        if (notSelectList[i].id == this.taskScoreUserlist[j].id) {
                            needRemoveTagList.push(this.taskScoreUserlist[j]);
                        }
                    }
                }
                //console.log("remove tag score user size:", needRemoveTagList.length );
                for (var i = 0, isize = needRemoveTagList.length; i < isize; i++) {
                    // tag 标签移除
                    this.handleTagScoreClose(needRemoveTagList[i]);
                }
            },
            // 打分人：把当前确认选择的打分人，删除单个的方法
            handleTagScoreClose(tag) {
                var canelSelectRow = undefined;
                for (var i = 0, size = this.$refs.scoreUserTable.selection.length; i < size; i++) {
                    // console.log("handleTagScoreClose",tag, this.$refs.scoreUserTable.selection[i]);
                    if (tag.id == this.$refs.scoreUserTable.selection[i].id) {
                        canelSelectRow = this.$refs.scoreUserTable.selection[i];
                    }
                }
                if (canelSelectRow != undefined) {
                    this.$refs.scoreUserTable.toggleRowSelection(canelSelectRow, false);
                }
                // tag 标签移除
                let index = this.taskScoreUserlist.indexOf(tag); // 标签索引
                this.taskScoreUserlist.splice(index, 1); // 移除标签

                this.taskScoreUserIdsRefresh();
            },
            taskScoreUserIdsRefresh() {
                console.log("taskScoreUserIdsRefresh");
                this.form.taskScoreUserIds = "";
                for (var i = 0, iSize = this.taskScoreUserlist.length; i < iSize; i++) {
                    this.form.taskScoreUserIds += this.taskScoreUserlist[i].id + ",";
                }
                if (this.form.taskScoreUserIds != "") {
                    this.form.taskScoreUserIds = this.form.taskScoreUserIds.substring(0, this.form.taskScoreUserIds.lastIndexOf(","));
                }
                console.log("taskScoreUserIdsRefresh：this.form.taskScoreUserIds", this.form.taskScoreUserIds);
            }

        }
    };
</script>
